package com.zwface.demo.function.attendance.mvvm;

import android.content.Context;
import android.os.Environment;
import android.view.View;

import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableInt;

import com.arcsoft.arcfacedemo.faceserver.FaceServer;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zwface.demo.App;
import com.zwface.demo.base.BaseViewModel;
import com.zwface.demo.greendao.AttendanceManager;
import com.zwface.demo.greendao.CourseManager;
import com.zwface.demo.greendao.UserInfoManager;
import com.zwface.demo.model.db.Attendance;
import com.zwface.demo.model.db.Course;
import com.zwface.demo.model.db.UserInfo;
import com.zwface.demo.utils.ExcelUtils;
import com.zwface.demo.utils.FastjsonHelper;
import com.zwface.demo.utils.SharedPreferenceUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * created by      张中文
 * on:             2020/4/28 13:41
 * 描述：
 */
public class AttendanceViewModel extends BaseViewModel
{
    //是否显示录入人脸按钮
    public ObservableBoolean isShowRegister = new ObservableBoolean(false);

    /**
     * 录入人脸
     */
    public void registerFace(String stuNo){
        String facePath = FaceServer.ROOT_PATH + File.separator + FaceServer.SAVE_IMG_DIR + File.separator + stuNo + FaceServer.IMG_SUFFIX;
        UserInfo userInfo = UserInfoManager.queryUserByNo(stuNo);
        userInfo.setFace(facePath);
        UserInfoManager.updateUser(userInfo);
        SharedPreferenceUtils.setParam(App.getInstance(),SharedPreferenceUtils.USER_FACE, facePath);

        if(!isShowRegister.get()){
            //签到
            sign(userInfo);
        }
    }

    /**
     * 签到
     */
    public void sign(UserInfo userInfo){
        Attendance attendance = new Attendance();
        attendance.setStuId(userInfo.getId());
        attendance.setStuName(userInfo.getName());
        attendance.setSignTime(TimeUtils.getNowString());
        attendance.setStuNo(userInfo.getStuNo());
        attendance.setFace(userInfo.getFace());
        attendance.setBuildTime(TimeUtils.getNowMills());

        Course course = getCourseByTime();
        if(course != null){
            attendance.setCourseId(course.getId());
            attendance.setCourseName(course.getCourseName());
        }
        AttendanceManager.addAttendance(attendance);
        ToastUtils.showShort("签到成功");
    }

    /**
     * 根据当前时间获取课程信息
     */
    private Course getCourseByTime(){
        Long curTime = TimeUtils.getNowMills();
        Calendar calendar = Calendar.getInstance();
        int weekDay = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (weekDay == 0) {
            weekDay = 7;
        }

        SimpleDateFormat format = TimeUtils.getSafeDateFormat("yyyy-MM-dd");
        String todayDate = TimeUtils.getNowString(format);
        long firstCourse = TimeUtils.string2Millis(todayDate+" 8:00:00");
        long secondCourse = TimeUtils.string2Millis(todayDate+" 9:00:00");
        long thirdCourse = TimeUtils.string2Millis(todayDate+" 10:00:00");
        long forthCourse = TimeUtils.string2Millis(todayDate+" 11:00:00");
        long fifthCourse = TimeUtils.string2Millis(todayDate+" 14:00:00");
        long sixthCourse = TimeUtils.string2Millis(todayDate+" 15:00:00");
        long seventhCourse = TimeUtils.string2Millis(todayDate+" 16:00:00");
        long eighthCourse = TimeUtils.string2Millis(todayDate+" 17:00:00");

        long legth = 45*60*1000;

        int courseIndex = 0;//节数
        if(curTime>=firstCourse && curTime <= firstCourse+legth){
            courseIndex = 1;
        }else if(curTime>=secondCourse && curTime <= secondCourse+legth){
            courseIndex = 2;
        }else if(curTime>=thirdCourse && curTime <= thirdCourse+legth){
            courseIndex = 3;
        }else if(curTime>=forthCourse && curTime <= forthCourse+legth){
            courseIndex = 4;
        }else if(curTime>=fifthCourse && curTime <= fifthCourse+legth){
            courseIndex = 5;
        }else if(curTime>=sixthCourse && curTime <= sixthCourse+legth){
            courseIndex = 6;
        }else if(curTime>=seventhCourse && curTime <= seventhCourse+legth){
            courseIndex = 7;
        }else if(curTime>=eighthCourse && curTime <= eighthCourse+legth){
            courseIndex = 8;
        }

        return CourseManager.queryCourseByTime(weekDay,courseIndex);
    }




    private ArrayList<ArrayList<String>> recordList;
    private static String[] title = { "学号","姓名","课程","时间" };
    private File file;
    private String fileName;

    /**
     * 导出excel
     * @param context
     */
    public void exportExcel(Context context,List<Attendance> attendances) {
        String todayDate = TimeUtils.millis2String(TimeUtils.getNowMills(),"yy-MM-dd");
        file = new File(getSDPath() + "/人脸考勤");
        makeDir(file);
        ExcelUtils.initExcel(file.toString() + "/"+todayDate+".xls", title);
        fileName = getSDPath() + "/人脸考勤/"+todayDate+".xls";
        ExcelUtils.writeObjListToExcel(getRecordData(attendances), fileName, context);
    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     * @return
     */
    private  ArrayList<ArrayList<String>> getRecordData(List<Attendance> attendances) {
        recordList = new ArrayList<>();
        for (int i = 0; i <attendances.size(); i++) {
            Attendance attendance = attendances.get(i);
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add(attendance.getStuNo());
            beanList.add(attendance.getStuName());
            beanList.add(StringUtils.isSpace(attendance.getCourseName())?"未知":attendance.getCourseName());
            beanList.add(attendance.getSignTime());
            recordList.add(beanList);
        }
        return recordList;
    }

    private  String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }

    private void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }
}
